<template>
  <div>
    <el-form ref="formRef" label-position="right" label-width="100px" :model="form" :rules="rules">
      <el-form-item label="部门名称" style="width:380px" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="部门编码" style="width:380px" prop="code">
        <el-input v-model="form.code" />
      </el-form-item>
      <el-form-item label="负责人" style="width:380px" prop="manager">
        <el-select v-model="form.manager">
          <el-option v-for="item in list" :key="item.id" :value="item.username" :label="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" style="width:380px" prop="introduce">
        <el-input v-model="form.introduce" />
      </el-form-item>
      <el-form-item>
        <el-button @click="close">取消{{ isEdit }}</el-button>
        <el-button type="primary" @click="submit">{{ isEdit?'编辑':'新增' }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmployeeSimple, addDepartments, getDepartmentById, updateDepartments } from '@/api/departments'
export default {
  // ------------------------------------------------------------------------------------------------------------------父组件传递的值
  props: {
    pid: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  // ------------------------------------------------------------------------------------------------------------------数据
  data() {
    // ---------------------------------------------------------------部门编码的自定义校验规则
    const validCode = (rule, value, callback) => {
      // 挑选出整体数组的code值
      let codeList = this.originList.map(item => item.code)
      // 如果当前状态是编辑，则编码要排除自身
      if (this.isEdit) {
        // 把当前正在编辑的部门编号（this.id）排除在外
        // 过滤掉当前的部门, map得到部门编号列表
        codeList = this.originList.filter(item => item.id !== this.pid).map(item => item.code)
      }
      // 如果输入的值已包含在数组中，则报错，否则执行
      codeList.includes(value) ? callback(new Error('该编码已被占用')) : callback()
    }
    // ---------------------------------------------------------------部门名字的自定义校验规则
    const validName = (rule, value, callback) => {
      // 不能取自己子级部门的名字
      let nameList = this.originList.filter(item => item.pid === this.pid).map(item => item.name)
      if (this.isEdit) {
        // 1. 找到当前被编辑的元素
        const dept = this.originList.find(item => item.id === this.pid)
        // 2. 取出pid(它的父级是谁)
        const pid = dept.pid
        // 3. 过滤： 同一个父级，不包括自己； map： 只要需要名字
        nameList = this.originList.filter(item => item.pid === pid && item.id !== this.pid).map(item => item.name)
      }
      // 如果输入的值已包含在数组中，则报错，否则执行
      if (nameList.includes(value)) {
        callback(new Error('此部门名已被占用'))
      } else {
        callback()
      }
    }
    return {
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      },
      // ---------------------------------------------------------------表单数据
      form: {
        code: '',
        introduce: '',
        manager: '',
        name: ''
      },
      // ---------------------------------------------------------------员工简单列表数据
      list: []
    }
  },
  // ------------------------------------------------------------------------------------------------------------------created钩子
  created() {
    // ---------------------------------------------------------------调用获取员工简单列表
    this.loadEmployeeSimple()
    if (this.isEdit) {
      this.loadDepartmentById()
    }
  },
  // ------------------------------------------------------------------------------------------------------------------方法
  methods: {
    // ---------------------------------------------------------------根据id查询部门信息
    async loadDepartmentById() {
      const res = await getDepartmentById(this.pid)
      // 数据回填
      this.form = res.data
    },
    // ---------------------------------------------------------------获取员工简单列表
    async loadEmployeeSimple() {
      // 调用封装函数
      const res = await getEmployeeSimple()
      // 绑定数据
      this.list = res.data
    },
    // ---------------------------------------------------------------新增部门
    async doAdd() {
      try {
        // 调用方法
        const res = await addDepartments({ ...this.form, pid: this.pid })
        // 弹窗提示
        this.$message.success(res.message)
        // 通知父组件成功
        this.$emit('success')
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    // ---------------------------------------------------------------修改部门
    async doEdit() {
      try {
        // 调用方法
        const res = await updateDepartments(this.form)
        // 弹窗提示
        this.$message.success(res.message)
        // 通知父组件成功
        this.$emit('success')
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    // ---------------------------------------------------------------提交表单
    async submit() {
      // 兜底校验
      this.$refs.formRef.validate(valid => {
        if (valid) {
          // 判断是编辑还是删除
          this.isEdit ? this.doEdit() : this.doAdd()
        }
      })
    },
    // ---------------------------------------------------------------取消功能
    close() {
      this.$emit('close')
    }
  }
}
</script>

<style>
</style>
